package com.mdd.maduoduo.utils;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;
import androidx.work.BackoffPolicy;
import androidx.work.Data;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.WorkRequest;

import com.mdd.maduoduo.R;

import java.util.concurrent.TimeUnit;

public class SmsUploadService extends Service {

    private static final String TAG = "SmsUploadService";
    private static final int NOTIFICATION_ID = 1001;
    private static final String CHANNEL_ID = "sms_upload_channel";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service created");
        createNotificationChannel();
//        startForegroundWithType();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service started");
        startForegroundWithType();
        if (intent != null && intent.hasExtra("sms_data")) {
            String smsJson = intent.getStringExtra("sms_data");
            Log.d(TAG, "Received SMS data: " + smsJson);
            uploadSmsData(smsJson);
        } else {
            Log.w(TAG, "No SMS data in intent");
        }

        // 保持服务存活
        return START_STICKY;
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    getString(R.string.notification_channel_name),
                    NotificationManager.IMPORTANCE_LOW);
            channel.setDescription(getString(R.string.notification_channel_description));
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    private void startForegroundWithType() {
        Notification notification = buildNotification();
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                int foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC |
                        ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE;
                startForeground(NOTIFICATION_ID, notification, foregroundServiceType);
            } else {
                startForeground(NOTIFICATION_ID, notification);
            }
        } catch (Exception e) {
            Log.e(TAG, "Start foreground failed", e);
        }
    }

    private Notification buildNotification() {
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle(getString(R.string.notification_title))
                .setContentText(getString(R.string.notification_text))
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .setOngoing(true)
                .build();
    }

    private void uploadSmsData(String smsJson) {
        try {
            Data inputData = new Data.Builder()
                    .putString("sms_json", smsJson)
                    .build();
            if (smsJson.contains("包裹")||smsJson.contains("快递")){
                OneTimeWorkRequest uploadWork = new OneTimeWorkRequest.Builder(SmsUploadWorker.class)
                        .setInputData(inputData)
                        .setBackoffCriteria(
                                BackoffPolicy.EXPONENTIAL,
                                WorkRequest.MIN_BACKOFF_MILLIS,
                                TimeUnit.MILLISECONDS)
                        .build();

                WorkManager.getInstance(this).enqueue(uploadWork);
            }
            Log.d(TAG, "Enqueued SMS upload work");
        } catch (Exception e) {
            Log.e(TAG, "Upload SMS data failed", e);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service destroyed");
    }
}
